﻿using MediatR;
using RearLivestock.Common.Domains.Common;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.Departmentss
{
    public class SearchDepartmentTreeHandler : IRequestHandler<SearchDepartmentTreeCommand, Result<List<CascaderDto>>>
    {
        /// <summary>
        /// 部门
        /// </summary>
        private readonly IBaseRepository<Departments> _departmentsRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchDepartmentTreeCommand> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentsRepository"></param>
        /// <param name="logger"></param>
        public SearchDepartmentTreeHandler(IBaseRepository<Departments> departmentsRepository, ILogger<SearchDepartmentTreeCommand> logger)
        {
            _departmentsRepository = departmentsRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取部门树形信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<List<CascaderDto>>> Handle(SearchDepartmentTreeCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<List<CascaderDto>>() { Code = (int)CommonErrorCode.Search };
            try
            {
                result.Code = (int)CommonErrorCode.Success;
                result.Data = GetCascaderDepartment(request.Pid);
                result.Msg = "获取部门树形成功";
            }
            catch (Exception ex)
            {
                result.Msg = "获取部门树形异常" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 级联获取部门区域
        /// </summary>
        /// <param name="Pid"></param>
        /// <returns></returns>
        public List<CascaderDto> GetCascaderDepartment(int Pid)
        {
            var cascader = new List<CascaderDto>();
            var department= _departmentsRepository.Query().ToList();
            cascader = department.Where(z => z.Pid == Pid).Select(z => new CascaderDto()
            {
                Value = z.DepartmentId,
                Label = z.DepartmentName,
                Children = GetCascaderDepartment(z.DepartmentId).Count > 0 ? GetCascaderDepartment(z.DepartmentId) : new List<CascaderDto>()
            }).ToList();
            return cascader;
        }
    }
}
